package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.AppUtil;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.form.service.impl.ScriptImpl;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.model.WQbdReportTemplate;
import com.ccp.dev.qbdms.service.WQbdReportTemplateService;
import com.ccp.dev.qbdms.util.WordUtils;
import com.ccp.dev.system.model.Dictionary;
import com.ccp.dev.system.service.DictionaryService;
import com.google.common.collect.Maps;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 报告模板管理 信息操作处理控制器
 *
 * @author milihao
 * @date 2020-06-22 15:26:43
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "报告模板管理")
@RequestMapping("/qbdms/wQbdReportTemplate")
public class WQbdReportTemplateController extends SysBaseController {

	@Resource
	private WQbdReportTemplateService wQbdReportTemplateService;
	@Resource
	private ScriptImpl scriptImpl;

	/**
	 * 功能描述: 跳转到首页
	 *
	 * @return: java.lang.String
	 * @auther: milihao
	 * @date: 2020-06-22 15:26:43
	 */
	@RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
	@Action(description = "跳转到报告模板管理首页", exectype = "页面跳转日志")
	public String viewList(Model model) {
		model.addAttribute("currentUserId", scriptImpl.getCurrentUserId());
		return "wQbdReportTemplate/list";
	}

	/**
	 * 功能描述: 附带检索条件的分页查询
	 *
	 * @param: [request] http请求
	 * @return: java.lang.Object
	 * @auther: milihao
	 * @date: 2020-06-22 15:26:43
	 */
	@RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
	@ResponseBody
	@Action(description = "附带检索条件的分页查询报告模板管理", detail = "查询数据信息<#if success>成功<#else></#if>")
	public Object list(HttpServletRequest request) {
		QueryFilter queryFilter = new QueryFilter(request, true);
		//分页数据
		queryFilter.addFilter("secret", scriptImpl.getCurrentUser().getPrivacyLevel());
		//queryFilter.addFilter("createBy", scriptImpl.getCurrentUser().getUserId());
		List<WQbdReportTemplate> pageDatas = wQbdReportTemplateService.queryList(queryFilter);
		SysAuditThreadLocalHolder.putParamerter("success", true);
		return JSON
				.toJSONStringWithDateFormat(success(pageDatas, queryFilter.getPageBean().getTotalCount()),
						"yyyy-MM-dd");
	}


	/**
	 * 功能描述: 跳转到新增页面
	 *
	 * @return: java.lang.String
	 * @auther: milihao
	 * @date: 2020-06-22 15:26:43
	 */
	@RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
	@Action(description = "跳转到报告模板管理新增页面", exectype = "页面跳转日志")
	public String viewAdd(HttpServletRequest request, ModelMap modelMap) {
		String id = RequestUtil.getString(request, "id");
		modelMap.put("id", id);
		return "wQbdReportTemplate/add";
	}

	/**
	 * 功能描述:  数据保存通用方法
	 *
	 * @param: wQbdReportTemplate 保存的对象
	 * @return: java.lang.Object
	 * @auther: milihao
	 * @date: 2020-06-22 15:26:43
	 */
	@RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
	@ResponseBody
	@Action(description = "保存报告模板管理数据", detail = "<#if isAdd>新增<#else>编辑</#if>报告模板管理数据<#if success>成功<#else>失败</#if>")
	public Object save(@RequestBody WQbdReportTemplate wQbdReportTemplate) {
		String id = wQbdReportTemplate.getId();
		SysAuditThreadLocalHolder.putParamerter("isAdd", true);
		wQbdReportTemplate.setId(UUIDUtils.getUUIDFor32());
		Date d = new Date();
		wQbdReportTemplate.setCreateTime(d);
		wQbdReportTemplate.setUpdateTime(d);
		wQbdReportTemplate.setCreateUser(scriptImpl.getCurrentUser().getFullName());
		wQbdReportTemplate.setCreateBy(scriptImpl.getCurrentUserId());
		ZhiLiangConst.addCommonFields(wQbdReportTemplate);
		int result = wQbdReportTemplateService.add(wQbdReportTemplate);

		if (result > 0) {
			SysAuditThreadLocalHolder.putParamerter("success", true);
		} else {
			SysAuditThreadLocalHolder.putParamerter("success", false);
		}
		return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
	}

	/**
	 * 功能描述: 跳转到详情页面
	 *
	 * @return: java.lang.String
	 * @auther: milihao
	 * @date: 2020-06-22 15:26:43
	 */
	@RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
	@Action(description = "跳转到报告模板管理详情页面", exectype = "页面跳转日志")
	public String viewParticulars(HttpServletRequest request, ModelMap modelMap) {
		String id = RequestUtil.getString(request, "id");
		modelMap.put("id", id);
		return "wQbdReportTemplate/particulars";
	}

	/**
	 * 功能描述: 根据主键id获取一条数据的通用查询方法
	 *
	 * @param: id 参数对象必须是"id"
	 * @return: java.lang.Object
	 * @auther: milihao
	 * @date: 2020-06-22 15:26:43
	 */
	@RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
	@ResponseBody
	@Action(description = "根据主键id查询报告模板管理的一条数据", detail = "根据主键id查询报告模板管理的数据<#if success>成功<#else>失败</#if>")
	public Object get(@RequestParam("id") String id) {
		WQbdReportTemplate wQbdReportTemplate = wQbdReportTemplateService.getOneById(id);
		if (null == wQbdReportTemplate) {
			SysAuditThreadLocalHolder.putParamerter("success", false);
			return getResultDataError("get.failure");
		}
		SysAuditThreadLocalHolder.putParamerter("success", true);
		return JSON.toJSONStringWithDateFormat(getResultDataSuccess("get.success", wQbdReportTemplate),"yyyy-MM-dd");
	}

	/**
	 * 功能描述: 根据主键ID删除数据的通用删除方法
	 *
	 * @param: id 参数名称必须是"id"
	 * @return: java.lang.Object
	 * @auther: milihao
	 * @date: 2020-06-22 15:26:43
	 */
	@PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
	@ResponseBody
	@Action(description = "根据主键ID删除报告模板管理数据", exectype = "删除日志", detail = "删除数据信息<#if success>成功<#else>失败</#if>")
	public Object delete(@RequestParam("id") String id) {
		if (StringUtil.isEmpty(id)) {
			SysAuditThreadLocalHolder.putParamerter("success", false);
			return fail("delete.failure.message");
		}

		//2020/7/2 zzy 删除过滤,只能删除自己创建的
		String userId = ContextUtil.getCurrentUserId();
		String[] ids = id.split(",");
		for (String key : ids) {
			WQbdReportTemplate data = wQbdReportTemplateService.getOneById(key);
			if (!userId.equals(data.getCreateBy())) {
				SysAuditThreadLocalHolder.putParamerter("success", false);
				return fail("删除失败，只能删除自己创建的数据！");
			}
		}

		int result = wQbdReportTemplateService.delByIdArray(id.split(","));
		if (result > 0) {
			SysAuditThreadLocalHolder.putParamerter("success", true);
		} else {
			SysAuditThreadLocalHolder.putParamerter("success", false);
		}
		return result > 0 ? getResultDataSuccess("delete.success")
				: getResultDataError("delete.failure");
	}

	/**
	 * 功能描述: 获取所有统计图数据
	 *
	 * @param: WQbdReportTemplate 实体
	 * @return: java.lang.Object
	 * @auther: milihao
	 * @date: 2020-06-23 15:26:43
	 */
	@RequestMapping("/getCharData")
	@ResponseBody
	@Action(description = "获取所有统计图数据", detail = "获取所有统计图数据<#if success>成功<#else>失败</#if>")
	public Object getCharData(String param,HttpServletRequest request) {
		QueryFilter queryFilter = new QueryFilter(request, false);
		List<Map<String, Object>> dataMapList = wQbdReportTemplateService
				.getCharData(JSON.parseObject(param, WQbdReportTemplate.class),queryFilter);
		SysAuditThreadLocalHolder.putParamerter("success", true);
		return success(dataMapList);
	}


	/**
	 * 下载生成的doc文件
	 * @auth zzy
	 */
	@RequestMapping("/downloadDoc")
	@Action(description = "下载报告模板", detail = "下载报告模板<#if success>成功<#else>失败</#if>")
	public void downloadDoc(HttpServletRequest request,HttpServletResponse response, String id)
			throws IOException, TemplateException {
		WQbdReportTemplate wQbdReportTemplate = wQbdReportTemplateService
				.getOneById(id);
		Map dataMap = Maps.newHashMap();
		dataMap.put("img1", wQbdReportTemplate.getChart1Bar().split(",")[1]);
		dataMap.put("year", "2020");
		dataMap.put("img2", wQbdReportTemplate.getChart2Bar().split(",")[1]);
		dataMap.put("img3", wQbdReportTemplate.getChart2Pie().split(",")[1]);
		dataMap.put("img4", wQbdReportTemplate.getChart3Bar().split(",")[1]);
		dataMap.put("img5", wQbdReportTemplate.getChart3Pie().split(",")[1]);
		dataMap.put("img6", wQbdReportTemplate.getChart4Bar().split(",")[1]);
		dataMap.put("img7", wQbdReportTemplate.getChart4Pie().split(",")[1]);
		dataMap.put("img8", wQbdReportTemplate.getChart5Bar().split(",")[1]);
		dataMap.put("img9", wQbdReportTemplate.getChart5Pie().split(",")[1]);
		dataMap.put("img10", wQbdReportTemplate.getChart7Bar().split(",")[1]);
		dataMap.put("img11", wQbdReportTemplate.getChart7Pie().split(",")[1]);
		dataMap.put("img12", wQbdReportTemplate.getChart6Bar().split(",")[1]);
		dataMap.put("img13", wQbdReportTemplate.getChart6Pie().split(",")[1]);


		JSONObject table1 = JSON.parseObject(wQbdReportTemplate.getTable1());
		if (null != table1) {
			List<Map<String, Object>> listMap = JSON
					.parseObject(table1.getString("data"), new TypeReference<List<Map<String, Object>>>() {
					});
			dataMap.put("table1", listMap);
		}

		// 前五位汇总表
		JSONObject tablejsonobj = JSON.parseObject(wQbdReportTemplate.getTable2());
		if (null != tablejsonobj) {
			List<Map<String, Object>> listMap = JSON.parseObject(tablejsonobj.getString("table2"),
					new TypeReference<List<Map<String, Object>>>() {
					});
			dataMap.put("table2", listMap);
		}
		JSONObject table3 = JSON.parseObject(wQbdReportTemplate.getTable3());
		if (null != table3) {
			List<Map<String, Object>> listMap = JSON
					.parseObject(table3.getString("data"), new TypeReference<List<Map<String, Object>>>() {
					});
			dataMap.put("table3", listMap);
		}
		DictionaryService dictionaryService = AppUtil.getBean(DictionaryService.class);
		List<Dictionary> dicList = dictionaryService.getDicByNodeKey("mj", false);
		String secret = "";
		for (Dictionary dictionary : dicList) {
			if (dictionary.getItemValue().equals(wQbdReportTemplate.getSecret())) {
				// 密级显示名称
				secret = dictionary.getItemName();
				break;
			}
		}
		try {
			WordUtils.exportMillCertificateWord(request, response, dataMap, "D:/doc_f/", "/test/test.ftl",
					secret);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
